package handlers

import (
	"github.com/gin-gonic/gin"
	"live-stream-pro/models"
	"strconv"
)

// 发布
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	like, _ := strconv.Atoi(c.PostForm("like"))
	if title == "" || content == "" || author == "" || like == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "视频内容不能为空",
		})
		return
	}
	data := models.Open{
		Title:   title,
		Content: content,
		Author:  author,
		Like:    like,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

// 列表
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	Offset := (page - 1) * size

	query := models.DB.Model(&models.Open{})

	var count int64
	query.Count(&count)

	var list []models.Open
	err := query.Offset(Offset).Limit(size).Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}

// 详情
func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Open
	err := models.DB.Where("id=?", id).First(&detail).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": detail,
	})
	return
}
